package ar.com.ford.it.fullEconomics.logic;

import java.sql.Timestamp;
import java.util.Collection;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.persistence.dao.CommodityPartDao;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp02Commodity;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp03Commodpart;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;

public class CommodityPartLogic {
    private static final String CLASS_NAME = CommodityPartLogic.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    public Teesp02Commodity getPartsEffectiveCommodity(Teesp01Part part)
            throws FullEconomicsException {

        String METHOD_NAME = "getPartsEffectiveCommodity";
        log.entering(CLASS_NAME, METHOD_NAME);

        Teesp02Commodity result = new Teesp02Commodity();
        CommodityPartDao dao = new CommodityPartDao();
        try {
            result = dao.getPartsEffectiveCommodity(part);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Parts Effective Commodity", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.CommodityParts.FINDBYNAME);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);

        return result;
    }

    public void createCommPart(Teesp02Commodity commodity, Teesp01Part part,
                               FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "createCommPart";
        log.entering(CLASS_NAME, METHOD_NAME);

        Teesp03Commodpart commPart = new Teesp03Commodpart();
        CommodityPartDao dao = new CommodityPartDao();
        try {
            PersistenceUtil.newTransaction();
            Teesp03Commodpart workingCopy = null;
            Teesp03Commodpart prevCommPart = null;
            commPart.setEesp03PlantCodeC(user.getTeesg01Plant());
            commPart.setEesp03CreateUserC(user.getId());
            commPart.setEesp03LastUpdtUserC(user.getId());
            commPart
                    .setEesp03CreateS(new Timestamp(System.currentTimeMillis()));
            commPart.setEesp03LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));
            commPart.setEesp03CommodPartOutDateY(FullEconomicsDateUtil
                    .maxDate());
            commPart.setTeesp02Commodity(commodity);
            commPart.setTeesp01Part(part);
            prevCommPart = dao.getPrevCommPart(commPart);
            if (prevCommPart != null) {
                if (prevCommPart.getTeesp02Commodity()
                        .getEesp02CommodityNumberK() != commPart
                        .getTeesp02Commodity().getEesp02CommodityNumberK()) {
                    workingCopy = (Teesp03Commodpart) dao
                            .getObjForUpdate(prevCommPart);
                    workingCopy.setEesp03LastUpdtUserC(user.getId());
                    workingCopy.setEesp03LastUpdtS(new Timestamp(System
                            .currentTimeMillis()));
                    workingCopy.setEesp03CommodPartOutDateY(new Timestamp(
                            System.currentTimeMillis()));
                }

            }
            commPart.setEesp03CommodPartInDateY(new Timestamp(System
                    .currentTimeMillis()));
            dao.createCommPart(commPart);
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Create Commodity Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.CommodityParts.CREATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    public void closeCommPart(Teesp02Commodity commodity, Teesp01Part part,
                              FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "createCommPart";
        log.entering(CLASS_NAME, METHOD_NAME);

        CommodityPartDao dao = new CommodityPartDao();
        try {
            PersistenceUtil.newTransaction();
            Teesp03Commodpart workingCopy = null;
            Teesp03Commodpart commPart = new Teesp03Commodpart();
            commPart.setTeesp01Part(part);
            commPart.setTeesp02Commodity(commodity);
            commPart.setEesp03PlantCodeC(user.getTeesg01Plant());
            commPart = dao.getEffectiveCommPart(commPart);
            workingCopy = (Teesp03Commodpart) dao.getObjForUpdate(commPart);
            workingCopy.setEesp03LastUpdtUserC(user.getId());
            workingCopy.setEesp03LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));
            workingCopy.setEesp03CommodPartOutDateY(new Timestamp(System
                    .currentTimeMillis()));
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Create Commodity Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.CommodityParts.CREATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    public void createCommParts(Teesp02Commodity commodity,
                                Collection<Teesp01Part> parts,
                                FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "createCommParts";
        log.entering(CLASS_NAME, METHOD_NAME);

        boolean notExistentPart = true;
        boolean closeCommPart = true;
        Collection<Teesp01Part> existingParts = this
                .findCommodityParts(commodity);
        for (Teesp01Part existingPart : existingParts) {
            for (Teesp01Part part : parts) {
                if (part.getEesp01PartClassCodeC().equals(
                        existingPart.getEesp01PartClassCodeC())
                        && part.getEesp01PartPrefixCodeC().equals(
                                existingPart.getEesp01PartPrefixCodeC())
                        && part.getEesp01PartBaseCodeC().equals(
                                existingPart.getEesp01PartBaseCodeC())
                        && part.getEesp01PartSuffixCodeC().equals(
                                existingPart.getEesp01PartSuffixCodeC())) {
                    closeCommPart = false;
                }
            }
            if (closeCommPart)
                this.closeCommPart(commodity, existingPart, user);
            closeCommPart = true;
        }
        for (Teesp01Part part : parts) {
            for (Teesp01Part existingPart : existingParts) {
                if (part.getEesp01PartClassCodeC().equals(
                        existingPart.getEesp01PartClassCodeC())
                        && part.getEesp01PartPrefixCodeC().equals(
                                existingPart.getEesp01PartPrefixCodeC())
                        && part.getEesp01PartBaseCodeC().equals(
                                existingPart.getEesp01PartBaseCodeC())
                        && part.getEesp01PartSuffixCodeC().equals(
                                existingPart.getEesp01PartSuffixCodeC())) {
                    notExistentPart = false;
                }
            }
            if (notExistentPart)
                this.createCommPart(commodity, part, user);
            notExistentPart = true;
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * 
     * @param commodity
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesp01Part> findCommodityParts(Teesp02Commodity commodity)
            throws FullEconomicsException {

        String METHOD_NAME = "findCommodityParts";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesp01Part> result = null;
        CommodityPartDao dao = new CommodityPartDao();
        try {
            result = dao.findCommodityParts(commodity);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Commodities parts", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.CommodityParts.FINDBYNAME);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);

        return result;
    }

    /**
     * Busca Commodity Parts validas en la fecha "date" para el Commodity
     * "commodity"
     * 
     * @param commodity
     * @param date
     * @return
     * @throws FullEconomicsException 
     */
    public Collection<Teesp03Commodpart> findCommodityPartsByDate(
                                                                  Teesp02Commodity commodity,
                                                                  Timestamp date)
            throws FullEconomicsException {
        String METHOD_NAME = "findCommodityPartsByDate";
        log.entering(CLASS_NAME, METHOD_NAME);
        Collection<Teesp03Commodpart> ret = null;
        
        CommodityPartDao dao = new CommodityPartDao();
        try {
            ret = dao.findCommodityPartsByDate(commodity, date);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Commodities parts by date", e);
            
            // FIXME Cambiar el PRS
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.CommodityParts.FINDBYNAME);
        }
        
        log.exiting(CLASS_NAME, METHOD_NAME);        
        return ret;
    }

}
